<template>
	<view>
		<view class="p-4 flex flex-column grid-gap-4">
			<view class="bg-white rounded-4">
				<input type="tel" class="p-4" placeholder="新手机号" v-model="form.mobile" maxlength="11">
			</view>
			<view class="bg-white rounded-4 flex flex-center pr-4" v-if="WEBCONFIG.imgcode">
				<input type="text" class="p-4 flex-1" placeholder="图形验证码" v-model="form.imgcode" maxlength="6">
				<image :src="captchaUrl" class="captcha-image flex-1" mode="scaleToFill" @tap="getCaptchaUrl" />
			</view>
			<view class="bg-white rounded-4 flex flex-center">
					<input type="tel" class="p-4 flex-1" placeholder="验证码" v-model="form.vcode" maxlength="6">
				<view class="h9 font-weight-600 p-4" @tap="getVcode"
					:class="vcodeBtn.disabled ? 'text-placeholder' : 'text-primary'">{{ vcodeBtn.text }}</view>
			</view>

			<view class="flex">
				<button class="flex-1 btn-primary btn-round" @tap="submit()">提交</button>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref,nextTick } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { useWebConfigStore, useUserStore, useRefs } from "@/stores";
import { $page, $api, $http, $message } from "@/utils";
const WebConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(WebConfigStore);
const UserStore = useUserStore();
const { USERINFO } = useRefs(UserStore);
const captchaUrl = ref('');
const form = ref({
	mobile: '',
	imgcode: '',
	vcode: '',
});
const vcodeBtn = ref({
	text: '获取验证码',
	disabled: false
});

const submit = () => {
	uni.showLoading({ title: '保存中...' });
	$api.User.mobile(form.value).then((res: any) => {
		uni.hideLoading();
		$api.User.userinfo(true);
		$message.success(res.msg);
		nextTick(() => {
			$page.back();
		})
	}).catch((err: any) => {
		uni.hideLoading();
		$message.error(err.msg);
	})
}
const getCaptchaUrl = () => {
	captchaUrl.value = $http.baseURL + 'Login/captcha?' + Math.random();
}
let timer: any = null;
const getVcode = () => {
	if (vcodeBtn.value.disabled) { return; }
	$api.Login.getVcode({
		mobile: form.value.mobile,
		imgcode: form.value.imgcode
	}).then((res: any) => {
		vcodeBtn.value.disabled = true;
		let time = 60;
		timer = setInterval(() => {
			vcodeBtn.value.text = `${time}s`;
			time--;
			if (time < 0) {
				clearInterval(timer);
				timer = null;
				vcodeBtn.value.text = '获取验证码';
				vcodeBtn.value.disabled = false;
			}
		}, 1000)
	}).catch((err: any) => {
		$message.error(err.msg);
	});
}
onLoad(() => {
	captchaUrl.value = $http.baseURL + 'Login/captcha';
});
onUnload(() => {
	if (timer) {
		clearInterval(timer);
	}
})
</script>

<style lang="scss" scoped>
.captcha-image {
	height: 50px;
}
</style>
